/*
	var t = new Essoft.Template();
	t.process({ tmpl: 'This is escaped: ${var|h} and this not: ${var}', data: {var: 'foo$'}, debug: false });
*/
// Create class
Essoft.Template = Class.create();
Essoft.Template.prototype = {

	// constructor
	initialize: function() {
		var params = Object.extend({
			document: document,
			base_url: undefined,
			debug: false,
			url: undefined,
			cache: true,
			tmpl: undefined,
			escape: true,
			template_script_id: 'template_script' 
		}, arguments[0]);
		this.params = params;
		this._cache = {};
		
		if ( this.params.url != undefined ) {
			this.load({url: this.params.url});
		}
	},

	/*
		url
	*/
	load: function(args) {

		// Check url and load template
		if ( args.url != undefined ) {

			// tmpl is already in cache
			if ( this._cache[args.url] != undefined && this.params.cache ) {
				this.params.tmpl = this._cache[args.url];
			}
			// fetch template
			else {
				this.params.tmpl = Essoft.Utils.makeGetPostRequest ({
			   		url: ( args.url.match(/^http/) ? '' : this.params.base_url) + args.url,
	    			async: false
				});
				// put template in cache
				if ( this.params.cache ) {
					this._cache[args.url] = this.params.tmpl;
				}
			}
		}
		// return tmpl
		return this.params.tmpl;
	},
	
	process: function() {
		var args = Object.extend({
			url: undefined,
			tmpl: this.params.tmpl,
			data: {},
			//re: /\$\{([^\}]*)\}/g,
			re: /\$\{\s*([^\}\|\s]*)\s*(\|\s*(h))?\s*\}/g,
			debug: false,
			escape: this.params.escape
		}, arguments[0]);
		return args.tmpl.replace(args.re, function (m,s1,s2,s3) { 
			if ( args.debug) { 
				alert(s1 + ': ' + args.data[s1])
			}; 
			//return ( s3 == 'h' ? encodeURIComponent(args.data[s1]) : args.data[s1] ) || '' 
			return ( args.data[s1] == undefined ? '' : ( s3 == 'h' ? encodeURIComponent(args.data[s1]) : args.data[s1] ) );
		});
	}

};
